//
// Created by dell on 2023/12/12.
//

#include "headers/user.h"
#include "headers/db/database.h"

int initDatabase() {
    // 读取文件初始化数据, 初始化数据库
    DB::init_data();
    return 0;
}


bool login(const std::string &username, const std::string &password) {
    if (!username.empty() && !password.empty()) {
        // 验证账户
        if (!account_checkout(username, password, 0).empty()) {
            printf("用户: [ %s ], 用户名密码正确\n", username.c_str());
            return true;
        }
        printf("login fail user: [ %s ] not found\n", username.c_str());
    }
    return false;
}


bool registration(const std::string &username, const std::string &password) {
    if (!username.empty() && !password.empty()) {
        // 验证账户
        std::string encryption_pass = account_checkout(username, password, 1);
        if (!encryption_pass.empty()) {
            std::map<std::string, std::string> insert_data;
            // 存入用户信息, 先判断用户是否被注册
            insert_data.insert(std::pair<std::string, std::string>(username, encryption_pass));
            DB::insert(insert_data);
            DB::refresh_database();
            printf("registered user: [ %s ] \n", username.c_str());
            return true;

        }
    }
    return false;
}


std::string account_checkout(const std::string &username, const std::string &password, int flag) {
    // 验证是否存在用户, 存在则对密码进行加密或者解密
    auto entry = db.find(username);
    char candidate_password[2 * MAX_STR_LEN] = {0};
    if (flag == 0) {
        if (db.end() != entry) {
            // login check
            // 解密密码
            std::string descPass = entry->second;
            CodeConvert::XorDecrypt((CUSTOM_BYTE *) candidate_password, (CUSTOM_BYTE *) descPass.c_str());
//            printf("解密后密码: %s", candidate_password);

            // 验证账户密码是否正确
            if (candidate_password == password) {
                return candidate_password;
            }
        }
    } else if (flag == 1) {
        // regis check
        if (db.end() == entry) {
            // 不存在该用户则可注册
            // 密码加密
            CodeConvert::XorEncrypt((CUSTOM_BYTE *) candidate_password, (CUSTOM_BYTE *) password.c_str());
            printf("加密后密码: %s \n", candidate_password);
            return candidate_password;
        }
    }
    return "";
}


